<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
    ok-text="测试连接并保存"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './dataSource.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    getAdminDataSourceEditPage,
    getAdminDataSourceUpdate,
    getAdminDataSourceCreate,
  } from '/@/api/flowManage/flowManage';

  export default defineComponent({
    name: 'DataSourceDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<any>({});
      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 110,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        dataRef.value = {};
        if (unref(isUpdate)) {
          const res = await getAdminDataSourceEditPage({ name: data?.record?.name });
          console.log('res', res);
          dataRef = {
            ...res,
          };
          setFieldsValue({
            ...unref(dataRef),
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          let formData = Object.assign({}, unref(dataRef), values);
          setDrawerProps({ confirmLoading: true });
          console.log(formData);
          if (unref(isUpdate)) {
            await getAdminDataSourceUpdate(formData);
          } else {
            await getAdminDataSourceCreate(formData);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
